import org.snmp4j.*;
import org.snmp4j.mp.MessageProcessingModel;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;
import org.snmp4j.util.PDUFactory;
import org.snmp4j.util.TableEvent;
import org.snmp4j.util.TableUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author SangLiang on 2018/6/19.
 * @version 1.0
 */



public class SnmpLinuxTest {


    /*    public static final String OID_PROCPERFCPU = ".1.3.6.1.2.1.25.5.1.1.1";
    public static final String OID_PROCPERFMEM = ".1.3.6.1.2.1.25.5.1.1.2";*/
    //.1.3.6.1.4.1.2021.11.50.0 原始用户CPU使用时间
    //.1.3.6.1.4.1.2021.11.51.0 原始nice占用时间
    //.1.3.6.1.4.1.2021.11.52.0 原始系统CPU使用时间
    //.1.3.6.1.4.1.2021.11.53.0 原始CPU空闲时间
    private static String[] oids = {
            //"1.3.6.1.2.1.25.5.1.1.1"
            //,
            "1.3.6.1.4.1.2021.11.50",
            "1.3.6.1.4.1.2021.11.51",
            "1.3.6.1.4.1.2021.11.52",
            "1.3.6.1.4.1.2021.11.53",
            "1.3.6.1.2.1.25.5.1.1.1"
    };


    private static String targetPid = "2728";


    public static void main(String[] args) {
        try {
            while (true) {
                CpuInfo cpuInfo1 = collectCPU();
                Thread.sleep(1000);
    /*            CpuInfo cpuInfo2 = collectCPU();

                long total = cpuInfo2.getTotal() - cpuInfo1.getTotal();
                if (total != 0) {
                    Double gate = 1.0 * (cpuInfo2.getProcess() - cpuInfo1.getProcess()) / total;
           *//*         BigDecimal cpuRadio = new BigDecimal(gate * 100);
                    double f1 = cpuRadio.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();*//*
                    if(gate>0){
                        System.out.println("cpu 占用："+gate*100);
                    }
                    // System.out.println("\n pid:" + targetPid + " cpu使用：" + cpuInfo1.getProcess() + "/"+cpuInfo1.getTotal()+"  占比:" + f1);
                } else {
                    //System.out.println("\n pid:" + targetPid + " cpu使用：" + cpuInfo2.getProcess() + "/"+cpuInfo2.getTotal() +"  占比:0");
                }*/
                //System.out.println(cpuInfo1.getProcess());


                Double radio =  ( cpuInfo1.getProcess())*100.0 / cpuInfo1.getTotal();
                System.out.println("\n pid:" + targetPid + " cpu使用：" + cpuInfo1.getProcess() + "/"+cpuInfo1.getTotal()+"  占比:" +radio);
            }

        } catch (Exception e) {

            System.out.println(e.getMessage());
        }
    }


    //获取cpu使用率
    public static CpuInfo collectCPU() {
        CpuInfo cpuInfo = new CpuInfo();

        TransportMapping transport = null;
        Snmp snmp = null;
        CommunityTarget target;

        try {
            transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);
            snmp.listen();
            target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setRetries(2);
            target.setAddress(GenericAddress.parse("udp:192.168.169.128/161"));
            target.setTimeout(8000);
            target.setVersion(SnmpConstants.version2c);
            TableUtils tableUtils = new TableUtils(snmp, new PDUFactory() {
                @Override
                public PDU createPDU(Target arg0) {
                    PDU request = new PDU();
                    request.setType(PDU.GET);
                    return request;
                }

                @Override
                public PDU createPDU(MessageProcessingModel messageProcessingModel) {
                    System.out.println("");
                    return null;
                }
            });

            OID[] columns = new OID[oids.length];
            for (int i = 0; i < oids.length; i++) {
                columns[i] = new OID(oids[i]);
            }

            List<TableEvent> list = tableUtils.getTable(target, columns, null, null);
            if (null != list && list.size() > 0) {
                Long totalTime = 0L;
               /*for (TableEvent event : list) {
                    Variable variable = event.getColumns()[4].getVariable();
                    totalTime += variable.toLong();
                }*/
                for(int i=0 ; i< 4; i++) {
                    Variable v =  list.get(0).getColumns()[i].getVariable();
                    totalTime += v.toLong();
                }
                cpuInfo.setTotal(totalTime);


                for (TableEvent event : list) {
                    OID oid = event.getIndex();
                    if (oid.toString().equalsIgnoreCase(targetPid)) {
                        Variable variable = event.getColumns()[4].getVariable();
                        cpuInfo.setProcess(variable.toLong());
                        return cpuInfo;
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (transport != null)
                    transport.close();
                if (snmp != null)
                    snmp.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        }
        return null;
    }
}
